package com.gkzf.ai.module.crm.service.creditreportsimple.app;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gkzf.ai.framework.common.util.object.BeanUtils;
import com.gkzf.ai.module.crm.controller.app.simpleCredit.vo.condition.UserAdmittanceConditionRespVO;
import com.gkzf.ai.module.crm.controller.app.simpleCredit.vo.condition.UserAdmittanceConditionSaveReqVO;
import com.gkzf.ai.module.crm.controller.app.simpleCredit.vo.house.UserAdmittanceHouseRespVO;
import com.gkzf.ai.module.crm.controller.app.simpleCredit.vo.vehicle.UserAdmittanceVehicleRespVO;
import com.gkzf.ai.module.crm.dal.dataobject.creditreportsimple.UserAdmittanceConditionDO;
import com.gkzf.ai.module.crm.dal.dataobject.creditreportsimple.UserAdmittanceHouseDO;
import com.gkzf.ai.module.crm.dal.dataobject.creditreportsimple.UserAdmittanceVehicleDO;
import com.gkzf.ai.module.crm.dal.mysql.creditreportsimple.UserAdmittanceConditionMapper;
import com.gkzf.ai.module.crm.dal.mysql.creditreportsimple.UserAdmittanceHouseMapper;
import com.gkzf.ai.module.crm.dal.mysql.creditreportsimple.UserAdmittanceVehicleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * CRM 小程序用户补充信息准入条件 Service 实现类
 *
 * @author 国科智飞
 */
@Service
@Slf4j
public class AppUserAdmittanceConditionServiceImpl implements AppUserAdmittanceConditionService {

    @Resource
    private UserAdmittanceConditionMapper userAdmittanceConditionMapper;

    @Resource
    private UserAdmittanceVehicleMapper userAdmittanceVehicleMapper;


    @Resource
    private UserAdmittanceHouseMapper userAdmittanceHouseMapper;
    @Override
    public void updateUserAdmittanceCondition(UserAdmittanceConditionSaveReqVO updateReqVO) {
        // 更新
        log.info("个人完善信息上传数据转换前:{}", JSON.toJSONString(updateReqVO));
        UserAdmittanceConditionDO updateObj = BeanUtils.toBean(updateReqVO, UserAdmittanceConditionDO.class);
        LambdaQueryWrapper<UserAdmittanceConditionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAdmittanceConditionDO::getUserOpenId, updateReqVO.getUserOpenId());
        updateObj.setLoanUses(Optional.ofNullable(getLoanUses(updateReqVO)).orElse(""));
        updateObj.setCreditReportJudicialType(Optional.ofNullable(getJudicialType(updateReqVO)).orElse(""));
        List<UserAdmittanceConditionDO> admittanceConditionDOList = userAdmittanceConditionMapper.selectList(queryWrapper);
        /*
          判断 二维码先填好  还是 先解析好
         */
        log.info("个人完善信息上传数据转换后:{}",JSON.toJSONString(updateObj));
        if (admittanceConditionDOList.isEmpty()){
            userAdmittanceConditionMapper.insert(updateObj);
        }else {

            userAdmittanceConditionMapper.update(updateObj,queryWrapper);
        }
    }

    /**
     * 更新贷款用途
     * @param updateReqVO 对象
     */
    public void updateLoanUses(UserAdmittanceConditionDO updateReqVO) {
        userAdmittanceConditionMapper.updateById(updateReqVO);
    }

    /**
     * 根据上下文计算可贷点
     * @param updateReqVO 补充信息对象
     * @return 可贷点字符串逗号隔开
     */
    public String getLoanUses(UserAdmittanceConditionSaveReqVO updateReqVO){
        StringBuilder loanUses = new StringBuilder();
        Integer isHave = 1;
        // 1是否纳税
        if (Objects.nonNull(updateReqVO.getIsPayTaxes()) && Objects.equals(updateReqVO.getIsPayTaxes(), isHave)) {
            loanUses.append(1+",");
        }
        // 2是否缴纳社保
        if (Objects.nonNull(updateReqVO.getIsSocialSecurity()) && Objects.equals(updateReqVO.getIsSocialSecurity(), isHave)) {
            loanUses.append(2+",");
        }
        // 3是否缴纳公积金
        if (Objects.nonNull(updateReqVO.getIsReserveFund()) && Objects.equals(updateReqVO.getIsReserveFund(), isHave)) {
            loanUses.append(3+",");
        }
        if (StringUtils.isNotBlank(loanUses)) {
            return loanUses.toString();
        }
        return null;
    }

    /**
     * 根据上下文获得司法类型
     * @return 返回司法类型字符串逗号隔开
     */
    public String getJudicialType(UserAdmittanceConditionSaveReqVO updateReqVO){
        String judicialType = "";
        if (Objects.nonNull(updateReqVO.getIsIllegalRecord()) && updateReqVO.getIsIllegalRecord() == 1){
            judicialType+="2,";
        }
        if (Objects.nonNull(updateReqVO.getIsDiscreditedPerson()) && updateReqVO.getIsDiscreditedPerson() == 1){
            judicialType+="1,";
        }
        return judicialType;
    }

    /**
     * 补充计算出来的信息
     *  如：身份证 年龄 性别 逾期 负债等数据无需手动填写
     * @param updateReqVO 对象
     */
    @Override
    public void updateUserAdmittanceConditionXml(UserAdmittanceConditionSaveReqVO updateReqVO) {
        // 更新
        UserAdmittanceConditionDO updateObj = BeanUtils.toBean(updateReqVO, UserAdmittanceConditionDO.class);
        LambdaQueryWrapper<UserAdmittanceConditionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAdmittanceConditionDO::getUserOpenId, updateReqVO.getUserOpenId());
        List<UserAdmittanceConditionDO> admittanceConditionDOList = userAdmittanceConditionMapper.selectList(queryWrapper);
        /*
          判断 二维码先填好  还是 先解析好
         */
        if (admittanceConditionDOList.isEmpty()){
            userAdmittanceConditionMapper.insertCondition(updateObj);
        }else {
            userAdmittanceConditionMapper.updateConditionById(updateObj);
        }
    }

    @Override
    public UserAdmittanceConditionDO getUserAdmittanceCondition(String userOpenId) {
        LambdaQueryWrapper<UserAdmittanceConditionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(UserAdmittanceConditionDO::getUserOpenId, userOpenId);
        List<UserAdmittanceConditionDO> conditionDOList = userAdmittanceConditionMapper.selectList(queryWrapper);
        if (!conditionDOList.isEmpty()){
            return conditionDOList.get(0);
        }
        return new UserAdmittanceConditionDO();
    }

    /**
     * 获取用户年收入
     * @param conditionDO 小程序用户补充信息
     * @return 年收入
     */
    @Override
    public BigDecimal getAnnualIncome(UserAdmittanceConditionDO conditionDO) {
        if (Objects.nonNull(conditionDO) && Objects.nonNull(conditionDO.getAnnualIncome())){
            return conditionDO.getAnnualIncome();
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取用户月收入
     * @param conditionDO 小程序用户补充信息
     * @return 月收入
     */
    @Override
    public BigDecimal getMonthlyIncome(UserAdmittanceConditionDO conditionDO) {
        if (Objects.nonNull(conditionDO) && Objects.nonNull(conditionDO.getAnnualIncome()) && conditionDO.getAnnualIncome().compareTo(BigDecimal.ZERO) > 0){
            // 月收入= 年收入/12
            return conditionDO.getAnnualIncome().divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取用户认定月收入
     * @param conditionDO 小程序用户补充信息
     * @return 认定月收入
     */
    @Override
    public BigDecimal getConcludeMonthlyIncome(UserAdmittanceConditionDO conditionDO,String trimmedType) {
            // 根据类型计算收入
            switch (trimmedType) {
                case "个税" -> {
                    // 月收入-个税：年度收入金额➗12
                    // 年收入不为空 并且 大于0
                    if (null != conditionDO.getAnnualIncome() && conditionDO.getAnnualIncome().compareTo(BigDecimal.ZERO) > 0) {
                        return conditionDO.getAnnualIncome().divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_UP);
                    }
                    return BigDecimal.ZERO;
                }
                case "公积金缴存基数" -> {
                    // 月收入-公积金缴存基数：用户填写公积金缴存基数
                    if (null != conditionDO.getCreditReportFundBase()) {
                        return BigDecimal.valueOf(conditionDO.getCreditReportFundBase());
                    }
                    return BigDecimal.ZERO;
                }
                case "社保缴存基数" -> {

                    if (null != conditionDO.getCreditReportSocialBase()) {
                        return BigDecimal.valueOf(conditionDO.getCreditReportSocialBase());
                    }
                    return BigDecimal.ZERO;
                }
                case "基于房产市值" -> {
                    List<UserAdmittanceHouseDO> houseDOList = userAdmittanceHouseMapper.selectByOpenIdList(conditionDO.getUserOpenId());
                    if (houseDOList.isEmpty()){
                        return BigDecimal.ZERO;
                    }
                    // 计算房产市值最大值
                    return houseDOList.stream()
                            .map(UserAdmittanceHouseDO::getHouseValue)
                            .max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                }
                case "基于按揭房月供" -> {
                    // ... 计算逻辑 取补充信息的按揭房月供...
                    List<UserAdmittanceHouseDO> houseDOList = userAdmittanceHouseMapper.selectByOpenIdList(conditionDO.getUserOpenId());
                    if (houseDOList.isEmpty()){
                        return BigDecimal.ZERO;
                    }
                    // 计算房产市值最大值
                    return houseDOList.stream()
                            .map(UserAdmittanceHouseDO::getMonthlyPayment)
                            .max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                }
                default -> {
                    log.warn("未知或未处理的月收入类型: {}", trimmedType);
                    return BigDecimal.ZERO;
                }
            }
    }

    /**
     * 获取用户个人资料
     * @param userOpenId 用户openId
     * @return 用户全部个人资料
     */
    @Override
    public UserAdmittanceConditionRespVO getUserAllAdmittanceCondition(String userOpenId) {
        LambdaQueryWrapper<UserAdmittanceConditionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(UserAdmittanceConditionDO::getUserOpenId, userOpenId);
        List<UserAdmittanceConditionDO> conditionDOList = userAdmittanceConditionMapper.selectList(queryWrapper);
        UserAdmittanceConditionRespVO conditionRespVO = new UserAdmittanceConditionRespVO();
        if (!conditionDOList.isEmpty()){
            BeanUtils.copyProperties(conditionDOList.get(0), conditionRespVO);
            List<UserAdmittanceVehicleDO> vehicleDOList = userAdmittanceVehicleMapper.selectByOpenIdList(userOpenId);
            List<UserAdmittanceHouseDO> houseDOList = userAdmittanceHouseMapper.selectByOpenIdList(userOpenId);
            List<UserAdmittanceVehicleRespVO> vehicleRespList = BeanUtils.toBean(vehicleDOList, UserAdmittanceVehicleRespVO.class);
            List<UserAdmittanceHouseRespVO> houseRespLiost = BeanUtils.toBean(houseDOList, UserAdmittanceHouseRespVO.class);
            conditionRespVO.setVehicleRespList(vehicleRespList);
            conditionRespVO.setHouseRespList(houseRespLiost);
            return conditionRespVO;
        }
        return conditionRespVO;
    }


}